package wzj.mybatisplusdemo.tools;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;

@Component
public class DatabaseOperationTool {

    private final SqlSessionFactory sqlSessionFactory;

    // 注入MyBatis的SqlSessionFactory
    @Autowired
    public DatabaseOperationTool(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    /**
     * 执行查询SQL
     *
     * @param sql 要执行的SQL语句
     * @return 查询结果列表
     */
    public List<Map<String, Object>> executeQuery(String sql) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            // 注意：这里的namespace需要与你的GenericMapper.xml中的namespace一致
            return session.selectList("wzj.mybatisplusdemo.mapper.GenericMapper.executeQuery", sql);
        } catch (Exception e) {
            throw new RuntimeException("SQL查询执行失败: " + sql + ", 错误: " + e.getMessage(), e);
        }
    }

    /**
     * 执行更新SQL（INSERT/UPDATE/DELETE）
     *
     * @param sql 要执行的SQL语句
     * @return 受影响的行数
     */
    public int executeUpdate(String sql) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) { // 自动提交事务
            // 注意：这里的namespace需要与你的GenericMapper.xml中的namespace一致
            return session.update("wzj.mybatisplusdemo.mapper.GenericMapper.executeUpdate", sql);
        } catch (Exception e) {
            throw new RuntimeException("SQL更新执行失败: " + sql + ", 错误: " + e.getMessage(), e);
        }
    }

    /**
     * 获取表结构信息
     *
     * @param tableName 表名
     * @return 表结构详情
     */
    public List<Map<String, Object>> getTableStructure(String tableName) {
        String sql = "SELECT COLUMN_NAME AS 列名, " +
                "DATA_TYPE AS 数据类型, " +
                "IS_NULLABLE AS 是否允许为空, " +
                "COLUMN_KEY AS 主键, " +
                "COLUMN_COMMENT AS 字段说明 " +
                "FROM INFORMATION_SCHEMA.COLUMNS " +
                "WHERE TABLE_NAME = '" + tableName + "' " +
                "ORDER BY ORDINAL_POSITION";
        return executeQuery(sql);
    }
}
